"""
@Author：十
@Time：2024/8/20 11:59
@FileName：fileRecognition.py
@Description：文件类型识别
"""
import csv
import re
import sqlite3
from datetime import datetime

import chardet
import pandas as pd
import win32com.client as win32
from PyQt5.QtCore import pyqtSignal, QObject
from loguru import logger


class fileRecognition(QObject):
    # 传递设备信息
    Signal_Get_instrument = pyqtSignal(object)

    def __init__(self, parent=None):
        super(fileRecognition, self).__init__(parent)

        self.parent = parent

    # 检测文件的编码类型
    def detect_encoding(self, file_path):
        with open(file_path, 'rb') as file:
            raw_data = file.read()
            result = chardet.detect(raw_data)
            encoding = result['encoding']
        return encoding

    # 识别设备
    # def Recognize(self, instrument):
    #     # print(instrument)
    #     file = "C:\\Users\\Administrator\\Desktop\\测试数据\\data"
    #
    #     if file:
    #         for root, dirs, files in os.walk(file):
    #             for file in files:
    #                 file_path = os.path.join(root, file)
    #                 file_extension = file.lower()
    #                 # print(file_path)
    #                 if instrument == '介损测试仪' and file_extension.endswith('.txt'):
    #                     self.DielectricLossRecognition(file_path)
    #                 elif instrument == '直流电阻测试仪' and file_extension.endswith('.txt'):
    #                     self.DirectCurrentResistance_txt(file_path)
    #                 # elif instrument == '直流电阻测试仪' and file_extension.endswith('.csv'):
    #                 #     try:
    #                 #         self.DirectCurrentResistance_csv(file_path)
    #                 #     except Exception as e:
    #                 #         print(e)
    #                 elif instrument == '直流系统测试仪' and file_extension.endswith('.txt'):
    #                     self.DC_System(file_path)
    #                 elif instrument == '高精度回路电阻测试仪' and file_extension.endswith('.doc'):
    #                     self.LoopResistanceTester(file_path)
    #                 elif instrument == 'SF6密度继电器校验仪' and file_extension.endswith('.txt'):
    #                     try:
    #                         self.SF6DensityRelayCalibrator(file_path)
    #                     except Exception as e:
    #                         print(e)

    # 介损
    def DielectricLossRecognition(self, file_path):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                preset_value = "***************************************"
                second_value = '测试方式'

                # 使用检测到的编码重新读取文件
                with open(file_path, 'r', encoding=encoding) as file:
                    if len(file.readlines()) > 8:
                        file.seek(0, 0)
                        content = file.read()
                        # 匹配首行
                        first_line = content.splitlines()[0] if content else ''
                        second_line = content.splitlines()[1][:4] if content else ''
                        if first_line == preset_value and second_line == second_value:
                            print(file_path)
                            self.insert_data_into_db(file_path)
        except Exception as e:
            print(f"无法读取文件: {file_path}\n错误: {str(e)}\n")

    # 解析文件并将数据插入数据库
    def insert_data_into_db(self, filename):
        conn = sqlite3.connect('./DB/digitization.db')
        cursor = conn.cursor()

        with open(filename, 'r', encoding='GB2312') as file:
            data = file.read().split('***************************************')

            for entry in data:
                lines = entry.strip().splitlines()
                if len(lines) < 13:
                    continue

                test_mode = lines[0].split(":")[1].strip()

                # 判断测试方式并分类处理
                if "CVT 同时测试" in test_mode and len(lines) >= 25:

                    test_time = lines[2].split(":")[1].strip() + " " + lines[3][13:]
                    test_voltage = float(lines[5].split(":")[1].strip().replace('kV', ''))
                    test_frequency = (lines[6].split(":")[1].strip().replace('Hz', ''))

                    c1_tgx = (lines[8].split(":")[1].strip().replace('%', '')).strip()
                    c1_cx = (lines[9].split(":")[1].strip().replace('nF', '')).strip()
                    c1_pf = (lines[10].split(":")[1].strip().replace('%', '')).strip()
                    c1_ix = (lines[11].split(":")[1].strip().replace('mA', '')).strip()
                    c1_pr = (lines[12].split(":")[1].strip().replace('mW', '')).strip()

                    c2_tgx = (lines[14].split(":")[1].strip().replace('%', ''))
                    c2_cx = (lines[15].split(":")[1].strip().replace('nF', ''))
                    c2_pf = (lines[16].split(":")[1].strip().replace('%', ''))
                    c2_ix = (lines[17].split(":")[1].strip().replace('mA', ''))
                    c2_pr = (lines[18].split(":")[1].strip().replace('mW', ''))

                    c12_tgx = (lines[20].split(":")[1].strip().replace('%', '')).strip()
                    c12_cx = (lines[21].split(":")[1].strip().replace('nF', '')).strip()
                    c12_pf = (lines[22].split(":")[1].strip().replace('%', '')).strip()
                    c12_ix = (lines[23].split(":")[1].strip().replace('mA', '')).strip()
                    c12_pr = (lines[24].split(":")[1].strip().replace('mW', '')).strip()

                elif "内标准 反接法 内高压" in test_mode and len(lines) >= 13:

                    test_time = lines[2].split(":")[1].strip() + " " + lines[3][13:]
                    test_voltage = (lines[5].split(":")[1].strip().replace('kV', ''))
                    test_frequency = (lines[6].split(":")[1].strip().replace('Hz', ''))

                    # C12字段使用测试数据，C1、C2为空
                    c1_tgx = c1_cx = c1_pf = c1_ix = c1_pr = None
                    c2_tgx = c2_cx = c2_pf = c2_ix = c2_pr = None

                    c12_tgx = (lines[8].split(":")[1].strip().replace('%', ''))
                    c12_cx = (lines[9].split(":")[1].strip().replace('pF', ''))
                    c12_pf = (lines[10].split(":")[1].strip().replace('%', ''))
                    c12_ix = (lines[11].split(":")[1].strip().replace('mA', ''))
                    c12_pr = (lines[12].split(":")[1].strip().replace('mW', ''))

                else:
                    continue  # 不符合条件的记录跳过

                cursor.execute('''INSERT INTO d_loss_data
                                (test_mode, test_time, test_voltage, test_frequency,
                                c1_tgx, c1_cx, c1_pf, c1_ix, c1_pr,
                                c2_tgx, c2_cx, c2_pf, c2_ix, c2_pr,
                                c12_tgx, c12_cx, c12_pf, c12_ix, c12_pr)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                               (test_mode, test_time, test_voltage, test_frequency,
                                c1_tgx, c1_cx, c1_pf, c1_ix, c1_pr,
                                c2_tgx, c2_cx, c2_pf, c2_ix, c2_pr,
                                c12_tgx, c12_cx, c12_pf, c12_ix, c12_pr))

        conn.commit()
        conn.close()

    # 直流电阻测试仪txt文件
    def DirectCurrentResistance_txt(self, file_path):
        data_list = []
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                preset_value = "    直阻仪测试记录"

            with open(file_path, 'r', encoding=encoding) as file:
                if len(file.readlines()) > 8:
                    file.seek(0, 0)
                    content = file.read()
                    first_line = content.splitlines()[0] if content else ''
                    if first_line == preset_value:
                        lines = content.splitlines()
                        for i in range(len(lines)):
                            line = lines[i].strip()
                            if line.startswith("P"):
                                test_time = lines[i + 1][5:]
                                test_mode = lines[i + 2].split(":")[1].strip()
                                test_number = (lines[i + 3].split(":")[1].strip())
                                test_electricity = (lines[i + 4].split(":")[1].strip().split(" ")[0])
                                resistor_AO = (lines[i + 7].split(":")[1].strip().split(" ")[0]).replace('mΩ', '')
                                resistor_BO = (lines[i + 8].split(":")[1].strip().split(" ")[0]).replace('mΩ', '')
                                resistor_CO = (lines[i + 9].split(":")[1].strip().split(" ")[0]).replace('mΩ', '')
                                if (lines[i + 10].split(":")[0].strip().split(" ")[0]) == '换算电阻':
                                    maximum_unbalance_rate = (lines[i + 14].split(":")[1].strip().split(" ")[0])
                                else:
                                    maximum_unbalance_rate = (lines[i + 10].split(":")[1].strip().split(" ")[0])
                                if all([test_time, test_mode, test_electricity, resistor_AO, resistor_BO, resistor_CO, maximum_unbalance_rate]):
                                    data = {
                                        'test_time': test_time,
                                        'test_mode': test_mode,
                                        'test_electricity': float(test_electricity),
                                        'resistor_ao': float(resistor_AO),
                                        'resistor_bo': float(resistor_BO),
                                        'resistor_co': float(resistor_CO),
                                        'max_unbalance_rate': float(maximum_unbalance_rate)
                                    }
                                    data_list.append(data)
                        if data_list is not None:
                            return data_list

        except Exception as e:
            print(f"无法读取文件: {file_path}\n错误: {str(e)}\n")
            logger.critical(f'读取直流电阻测试仪文件失败: {file_path}')

    # 直流电阻已经存在的数据
    def DCR_existing_data(self):
        try:
            existing_data = []
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            cursor.execute("SELECT test_time, test_mode, test_electricity, resistor_ao, resistor_bo, resistor_co, maximum_unbalance_rate FROM dcr_data")
            for row in cursor.fetchall():
                data = {
                    'test_time': row[0],
                    'test_mode': row[1],
                    'test_electricity': row[2],
                    'resistor_ao': row[3],
                    'resistor_bo': row[4],
                    'resistor_co': row[5],
                    'max_unbalance_rate': row[6]
                }
                existing_data.append(data)
            connection.close()
            return existing_data
        except Exception as e:
            print('从数据库中读取直流电阻测试仪已存在数据失败：', e)
            logger.critical('从数据库中读取直流电阻测试仪已存在数据失败:', e)

    # 直流电阻数据插入数据库
    def DCR_Insert(self, data):
        try:
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()

            cursor.execute("""
                INSERT OR IGNORE INTO dcr_data (test_time, test_electricity, test_mode, resistor_ao, resistor_bo, resistor_co, maximum_unbalance_rate, has_report)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """, (data['test_time'], data['test_electricity'], data['test_mode'], data['resistor_ao'],
                  data['resistor_bo'], data['resistor_co'], data['max_unbalance_rate'], 1))

            connection.commit()
            connection.close()
        except Exception as e:
            print('向数据库中插入直流电阻数据失败：', e)
            logger.critical('向数据库中插入直流电阻数据失败:', e)

    # def eventFilter(self, obj, event):
    #     if obj == self.edit_label:
    #         if event.type() == event.Enter:
    #             self.edit_label.setStyleSheet("color: red;")
    #         elif event.type() == event.Leave:
    #             self.edit_label.setStyleSheet("color: black;")
    #         elif event.type() == event.MouseButtonPress:
    #             self.save_to_database()
    #     return super().eventFilter(obj, event)

    # 直流电阻测试仪csv文件
    def DirectCurrentResistanceCSV(self, file_path):
        # 处理每组以 'Date' 开头的数据并打印结果
        with open(file_path, 'rb') as f:
            result = chardet.detect(f.read(1000))

        # 读取 CSV 文件，没有表头
        df = pd.read_csv(file_path, header=None, encoding=result['encoding'])
        df.columns = [f"Column{i + 1}" for i in range(df.shape[1])]

        def split_into_groups(df):
            # 根据 'Date' 开头的行将 DataFrame 分组
            groups = []
            current_group = []

            # 遍历每一行
            for _, row in df.iterrows():
                if 'Date' in row.values:  # 如果行中包含 'Date'，则开始新组
                    if current_group:
                        groups.append(pd.DataFrame(current_group))
                        current_group = []
                current_group.append(row)

            # 添加最后一组
            if current_group:
                groups.append(pd.DataFrame(current_group))

            return groups

        def process_group(group):
            # 连接数据库
            conn = sqlite3.connect('./DB/digitization.db')
            cursor = conn.cursor()

            """处理每个组的逻辑"""
            group = group.reset_index(drop=True)

            # 检查 group 是否有足够的行
            if len(group) < 4:
                print(f"Warning: Group has only {len(group)} rows, expected at least 4.")
                return  # 跳过行数不足的组

            # 提取测试时间（假设第一行第二列是测试时间）
            test_time = group.iloc[0, 1] if len(group.columns) > 1 else None

            # 提取测试模式和电流值
            try:
                test_mode = group.iloc[3, 0]  # 第四行第一列

            except IndexError as e:
                print(f"Error accessing test mode or electricity: {e}")
                return

            # 初始化电阻值
            test_electricity = resistor_AO = resistor_BO = resistor_CO = maximum_unbalance_rate = 0

            try:
                if test_mode == "Single-Test":
                    resistor_AO = group.iloc[6, 1].replace('m次', '') if len(group) > 4 and not pd.isna(group.iloc[4, 1]) else 0
                    test_electricity = group.iloc[4, 1].strip().replace('A', '') if len(group.columns) > 1 else None
                elif test_mode == "YN-Three-Test":
                    test_electricity = group.iloc[4, 0].strip().replace('I=', '').replace('A', '') if len(group.columns) > 1 else None
                    resistor_AO = group.iloc[6, 1].replace('m次', '')
                    resistor_BO = group.iloc[6, 2].replace('m次', '')
                    resistor_CO = group.iloc[6, 3].replace('m次', '')
                    maximum_unbalance_rate = group.iloc[6, 4].strip().replace('%', '')
                elif test_mode == 'Assist-Three-Test':
                    test_electricity = group.iloc[4, 1].strip().replace('A', '') if len(group.columns) > 1 else None
                    resistor_AO = group.iloc[6, 1].replace('m次', '')
                    resistor_BO = group.iloc[6, 2].replace('m次', '')
                    resistor_CO = group.iloc[6, 3].replace('m次', '')
                    maximum_unbalance_rate = group.iloc[6, 4].strip().replace('%', '')
            except Exception as e:
                print(f"Error processing resistor values: {e}")

            # 插入前查询是否有重复项
            cursor.execute('''
                SELECT COUNT(*) FROM dcr_data
                WHERE test_time = ? AND test_mode = ? AND test_electricity = ? AND resistor_AO = ? AND resistor_BO = ? AND resistor_CO = ? AND maximum_unbalance_rate = ?
            ''', (test_time, test_mode, test_electricity, resistor_AO, resistor_BO, resistor_CO, maximum_unbalance_rate))

            # 获取查询结果
            count = cursor.fetchone()[0]
            if count == 0:
                # 插入数据库
                cursor.execute('''INSERT OR IGNORE INTO dcr_data
                                (test_mode, test_time, test_electricity, resistor_AO,
                                resistor_BO, resistor_CO, maximum_unbalance_rate)
                                VALUES (?, ?, ?, ?, ?, ?, ?)''',
                               (test_mode, test_time, test_electricity, resistor_AO,
                                resistor_BO, resistor_CO, maximum_unbalance_rate))
                # 打印处理结果
                # print(f"Test Time: {test_time}\nTest Mode: {test_mode}")
                # print(f"Electricity: {test_electricity}\nAO: {resistor_AO}, BO: {resistor_BO}, CO: {resistor_CO}")
                # print(f"Maximum Unbalance Rate: {maximum_unbalance_rate}")
                # 
                # print('----------------------------')
            conn.commit()
            conn.close()

        try:
            groups = split_into_groups(df)
            for idx, group in enumerate(groups):
                process_group(group)
        except Exception as e:
            print('读取直流电阻csv文件失败：', e)

    def DirectCurrentResistance_csv(self, file_path):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read(1000)
                result = chardet.detect(raw_data)
                encoding = result['encoding']
            try:
                with open(file_path, 'r', newline='', encoding=encoding) as f:
                    reader = csv.reader(f)
                    first_row = next(reader, None)
                    if first_row and first_row[0] == "Date":
                        self.DirectCurrentResistanceCSV(file_path)

            except UnicodeDecodeError as e:
                print(f"无法读取文件: {file_path}, 错误: {e}")

        except Exception as e:
            print(e)

    # 直流系统测试仪
    # 稳压纹波
    def DC_System(self, file_path):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                preset_value = "                  直流系统综合特性测试仪稳压纹波精度测试历史数据"
                with open(file_path, 'r', encoding=encoding) as file:
                    if len(file.readlines()) > 2:
                        file.seek(0, 0)
                        content = file.read()
                        # 匹配首行
                        first_line = content.splitlines()[0] if content else ''

                        if first_line == preset_value:
                            test_time = content.splitlines()[3][4:22]
                            setting_current = content.splitlines()[3][29:37]
                            setting_voltage = content.splitlines()[3][43:51]
                            actual_current = content.splitlines()[3][57:]
                            data = content.splitlines()[5][:]
                            # 测定的稳压纹波电压是带“V”单位的数值，其余的数值含义暂不清楚
                            voltages = [float(value[:-1]) for value in data.split(',') if value.endswith('V')]
                            # print(test_time)
                            # print(setting_current)
                            # print(setting_voltage)
                            # print(actual_current)
                            # print(voltages)

        except Exception as e:
            print(f"无法读取文件: {file_path}\n错误: {str(e)}\n")

    # TODO：高精度回路电阻测试仪
    # 延时大
    def LoopResistanceTester_DOC(self, file_path):
        data_list = []
        try:
            word = win32.Dispatch("Word.Application")
            doc = word.Documents.Open(file_path)
            first_paragraph = doc.Paragraphs(1).Range.Text.strip()

            if first_paragraph == "* * * * 回路电阻测试数据 * * * *":
                # print(file_path)
                # print(f"匹配的 .doc 文件: {file_path}\n首行内容: {first_paragraph}\n")
                test_time = doc.Paragraphs(2).Range.Text.strip()[6:] + doc.Paragraphs(3).Range.Text.strip()[6:].strip().replace('', '')
                parsed_time = datetime.strptime(test_time, "%Y年%m月%d日%H时%M分%S秒")
                test_time = parsed_time.strftime("%Y-%m-%d %H:%M:%S")

                resistor = doc.Paragraphs(10).Range.Text.strip()[6:].strip().replace('uΩ', '')
                voltage = doc.Paragraphs(11).Range.Text.strip()[6:].strip().replace('mV', '')
                current = doc.Paragraphs(12).Range.Text.strip()[6:].strip().replace('mA', '')

                # print(test_time, resistor, voltage, current)

                if all([test_time, resistor, voltage, current]):
                    data = {
                        'test_time': test_time,
                        'resistor': float(resistor),
                        'voltage': float(voltage),
                        'current': float(current)
                    }
                    data_list.append(data)

            doc.Close()
            word.Quit()

            if len(data_list) > 0:
                return data_list

        except Exception as e:
            print(f"无法读取 .doc 文件: {file_path}\n错误: {str(e)}\n")

    # 回路电阻已经存在的数据
    def LR_existing_data(self):
        try:
            existing_data = []
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            cursor.execute("SELECT test_time, resistance, current, voltage FROM loop_resistance_data")
            for row in cursor.fetchall():
                data = {
                    'test_time': row[0],
                    'resistance': row[1],
                    'current': row[2],
                    'voltage': row[3]
                }
                existing_data.append(data)
            connection.close()
            return existing_data
        except Exception as e:
            print('从数据库中读取回路电阻测试仪已存在数据失败', e)
            logger.critical('从数据库中读取回路电阻测试仪已存在数据失败:', e)

    # 回路电阻数据插入数据库
    def LR_Insert(self, data):
        try:
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()

            cursor.execute("""
                INSERT OR IGNORE INTO loop_resistance_data (test_time, resistance, current, voltage, has_report)
                VALUES (?, ?, ?, ?, ?)
            """, (data['test_time'], data['resistance'], data['current'], data['voltage'], 1))

            connection.commit()
            connection.close()
        except Exception as e:
            print('向数据库中插入回路电阻数据失败：', e)
            logger.critical('向数据库中插入回路电阻数据失败:', e)

    # 接地导通
    def EarthContinuity_TXT(self, file_path):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                preset_value = "试品型号："

            with open(file_path, 'r', encoding=encoding) as file:
                if len(file.readlines()) > 3:
                    file.seek(0, 0)
                    content = file.read()
                    first_line = content.splitlines()[0] if content else ''
                    if first_line == preset_value:
                        # 将"I"替换为"0"
                        data = content.replace("I", "0")

                        # 按"试品型号："分割数据
                        items = data.split("试品型号：")[1:]  # 取出第一项后面的数据

                        result = []

                        for item in items:
                            lines = item.strip().splitlines()
                            test_data = {}

                            for line in lines:
                                if "测量电流" in line:
                                    test_data['current'] = float(line.split("：")[-1].strip().split()[0]) * 1000
                                elif "测试电阻" in line:
                                    test_data['resistor'] = float(line.split("：")[-1].strip().split()[0])
                                elif "时间" in line:
                                    old_time_str = line.split("：")[-1].strip().split()[1]
                                    input_format = "%Y年%m月%d日%H时%M分"
                                    datetime_obj = datetime.strptime(old_time_str, input_format)
                                    output_format = "%Y-%m-%d %H:%M:%S"
                                    test_data['test_time'] = datetime_obj.strftime(output_format)
                            result.append(test_data)
                        print(result)
                        return result
        except Exception as e:
            print(f"无法读取文件: {file_path}\n错误: {str(e)}\n")
            logger.critical(f'读取接地导通测试仪文件失败: {file_path}')

    # 接地导通已经存在的数据
    def EC_existing_data(self):
        try:
            existing_data = []
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            cursor.execute("SELECT test_time, current, resistance FROM earth_continuity")
            for row in cursor.fetchall():
                data = {
                    'test_time': row[0],
                    'current': row[1],
                    'resistance': row[2]
                }
                existing_data.append(data)
            connection.close()
            return existing_data
        except Exception as e:
            print('从数据库中读取接地导通仪已存在数据失败：', e)
            logger.critical('从数据库中读取接地导通仪已存在数据失败:', e)

    # 直流电阻数据插入数据库
    def EC_Insert(self, data):
        try:
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()

            cursor.execute("""
                INSERT OR IGNORE INTO earth_continuity (test_time, current, resistance, has_report)
                VALUES (?, ?, ?, ?)
            """, (data['test_time'], data['current'], data['resistance'], 1))
            connection.commit()
            connection.close()
        except Exception as e:
            print('向数据库中插入接地导通数据失败：', e)
            logger.critical('向数据库中插入接地导通数据失败:', e)

    # SF6密度继电器校验仪
    def SF6DensityRelayCalibrator(self, file_path):
        try:
            results = []
            current_data = {}

            conn = sqlite3.connect('./DB/digitization.db')
            cursor = conn.cursor()

            with open(file_path, 'rb') as file:
                raw_data = file.read(1000)
            result = chardet.detect(raw_data)

            with open(file_path, 'r', encoding=result['encoding']) as file:
                lines = file.readlines()

            for line in lines:
                if "infor=" in line:
                    match_time = re.search(r'infor=.+?,(\d{4}-\d{1,2}-\d{1,2} \d{2}:\d{2}:\d{2})', line)
                    if match_time:
                        current_data['时间'] = match_time.group(1)

                if "Flag=" in line:
                    flag_values = re.search(r'Flag=(.+)', line)
                    if flag_values:
                        current_data['Flag'] = flag_values.group(1)

                # 匹配每个Data的状态
                if "Data0=" in line:
                    current_data['Data0状态'] = self.extract_data_status(line)
                if "Data1=" in line:
                    current_data['Data1状态'] = self.extract_data_status(line)
                if "Data2=" in line:
                    current_data['Data2状态'] = self.extract_data_status(line)
                if "Data3=" in line:
                    current_data['Data3状态'] = self.extract_data_status(line)

                # 当遇到新的组数据开始时，保存当前组数据并打印
                if line.startswith("[") and current_data:
                    results.append(current_data)
                    # print(f"第{len(results)}组数据:")
                    # print(f"时间: {current_data.get('时间')}")
                    # print(f"Flag: {current_data.get('Flag')}")
                    # print(f"Data0状态: {current_data.get('Data0状态')}")
                    # print(f"Data1状态: {current_data.get('Data1状态')}")
                    # print(f"Data2状态: {current_data.get('Data2状态')}")
                    # print(f"Data3状态: {current_data.get('Data3状态')}")
                    # print("-----------------------")
                    # 插入数据到数据库
                    cursor.execute('''INSERT OR IGNORE INTO sf6_dr_data (test_time, flag, state1, state2, state3, state4)VALUES (?, ?, ?, ?, ?, ?)''',
                                   (current_data.get('时间'), current_data.get('Flag'), current_data.get('Data0状态'), current_data.get('Data1状态'), current_data.get('Data2状态'),
                                    current_data.get('Data3状态')))
                    current_data = {}

            conn.commit()
            conn.close()
        except Exception as e:
            print('读SF6密度继电器检验仪文件失败：', e)

    def extract_data_status(self, line):
        if "报警" in line:
            return "报警"
        elif "闭锁" in line:
            return "闭锁"
        elif '额定' in line:
            return '额定'
        elif "--" in line:
            return "无状态"
        else:
            return "无状态"

    # SF6气体综合分析仪
    def SF6GasAnalyzer(self, file_path):
        pass

    # 继电保护测试仪
